package com.cwf.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cwf.common.enums.BaseStateEnum;
import com.cwf.common.enums.IsDeleteEnum;
import com.cwf.common.enums.ResCodeEnum;
import com.cwf.common.exception.base.MyException;
import com.cwf.framework.redis.RedisService;
import com.cwf.system.dao.RolePermissionRelationDao;
import com.cwf.system.entity.Permission;
import com.cwf.system.entity.Role;
import com.cwf.system.entity.RolePermissionRelation;
import com.cwf.system.service.PermissionService;
import com.cwf.system.service.RolePermissionRelationService;
import com.cwf.system.service.RoleService;
import com.cwf.system.validation.role.AllotRolePermissionParams;
import com.cwf.system.vo.PermissionTreeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (RolePermissionRelation)表服务实现类
 *
 * @author makejava
 * @since 2023-02-23 18:43:10
 */
@Service("rolePermissionRelationService")
public class RolePermissionRelationServiceImpl extends ServiceImpl<RolePermissionRelationDao, RolePermissionRelation> implements RolePermissionRelationService {

    @Autowired
    RolePermissionRelationDao rolePermissionRelationDao;

    @Autowired
    PermissionService permissionService;

    @Autowired
    RoleService roleService;

    private ThreadLocal<List<Long>> key = new ThreadLocal<>();

    @Autowired
    RedisService redisService;


    @Override
    public List<PermissionTreeVO> getRolePermissionTree(Long id) {
        List<Permission> rolePermission = rolePermissionRelationDao.getRolePermission(id);
        if (rolePermission.size() == 0) {
            throw new MyException("当前角色下没有权限", ResCodeEnum.QUERY_ERR.getCode());
        }
        List<PermissionTreeVO> list = PermissionServiceImpl.formatPageTree(PermissionTreeVO.toVOList(rolePermission));

        return list;
    }


    @Override
    public List<Long> getRolePermissionIdList(Long id) {

        List<Permission> rolePermission = rolePermissionRelationDao.getRolePermission(id);

        List<Long> idList = rolePermission.stream().map(Permission::getId).sorted(Comparator.comparing(v -> v)).collect(Collectors.toList());
        if (idList.size() == 0) {
            throw new MyException("当前角色下没有权限", ResCodeEnum.QUERY_ERR.getCode());
        }
        return idList;
    }


    @Override
    @Transactional
    public boolean allotRolePermission(AllotRolePermissionParams params) {



        params.getAddIdList().forEach(add->{
            params.getDeleteIdList().forEach(del->{
                if (add==del){
                    throw new MyException("添加/删除不能有重复值",ResCodeEnum.UPDATE_ERR.getCode());
                }
            });
        });



        /**
         * 查询当前角色是否存在
         */
        LambdaQueryWrapper<Role> queryRole = new LambdaQueryWrapper<>();
        queryRole
                .eq(Role::getRoleId,params.getRoleId())
                .eq(Role::getIsDelete,IsDeleteEnum.NO.getCode())
                .eq(Role::getState, BaseStateEnum.OK.getCode());

        List<Role> roleList = roleService.list(queryRole);
        if (roleList.size()==0){
            throw new MyException("当前角色不存在/状态不可用",ResCodeEnum.UPDATE_ERR.getCode());
        }


        /**
         * 分配权限
         */
        if (params.getAddIdList().size() != 0) {


            //查询当前角色添加的权限id是否存在
            LambdaQueryWrapper<RolePermissionRelation> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper
                    .in(RolePermissionRelation::getPId, params.getAddIdList())
                    .eq(RolePermissionRelation::getRId, params.getRoleId())
                    .eq(RolePermissionRelation::getIsDelete,IsDeleteEnum.NO.getCode());

            List<RolePermissionRelation> list = this.list(lambdaQueryWrapper);

            List<Long> pidList = list.stream().map(RolePermissionRelation::getPId).collect(Collectors.toList());

            //如果存在
            if (pidList.size() != 0) {
                LambdaQueryWrapper<Permission> permissionLambdaQueryWrapper = new LambdaQueryWrapper<>();

                permissionLambdaQueryWrapper.in(Permission::getId, pidList);

                List<Permission> list1 = permissionService.list(permissionLambdaQueryWrapper);

                String msg = "";

                for (Permission permission : list1) {
                    msg += permission.getTitle() + ",";
                }

                throw new MyException(msg + "已经添加过了", ResCodeEnum.UPDATE_ERR.getCode());
            } else {

                List<RolePermissionRelation> collect = params.getAddIdList().stream().map(v -> RolePermissionRelation.builder()
                        .rId(params.getRoleId())
                        .pId(v).build()).collect(Collectors.toList());

                return this.saveBatch(collect);

            }


        }












        if (params.getDeleteIdList().size() != 0) {

            LambdaQueryWrapper<RolePermissionRelation> rolePermissionRelationLambdaQueryWrapper = new LambdaQueryWrapper<>();

            rolePermissionRelationLambdaQueryWrapper
                    .select(RolePermissionRelation::getId)
                    .in(RolePermissionRelation::getPId,params.getDeleteIdList())
                    .eq(RolePermissionRelation::getIsDelete,IsDeleteEnum.NO.getCode())
                    .eq(RolePermissionRelation::getRId,params.getRoleId());

            List<Long> idList = this.list(rolePermissionRelationLambdaQueryWrapper).stream().map(v -> v.getId()).collect(Collectors.toList());

            LambdaUpdateWrapper<RolePermissionRelation> rolePermissionRelationLambdaUpdateWrapper = new LambdaUpdateWrapper<>();

            rolePermissionRelationLambdaUpdateWrapper
                    .in(RolePermissionRelation::getId,idList)
                    .set(RolePermissionRelation::getIsDelete,IsDeleteEnum.OK.getCode());

            return this.update(rolePermissionRelationLambdaUpdateWrapper);




        }


        return false;
    }


    @Override
    public List<Long> treeSelect(Long roleId) {

        List<Long> rolePermissionIdList = this.getRolePermissionIdList(roleId);

        LambdaQueryWrapper<Permission> permissionLambdaQueryWrapper = new LambdaQueryWrapper<>();

        permissionLambdaQueryWrapper.eq(Permission::getIsDelete,IsDeleteEnum.NO.getCode())
                .eq(Permission::getState,BaseStateEnum.OK.getCode());

        List<Permission> list = permissionService.list(permissionLambdaQueryWrapper);


       test(PermissionServiceImpl.formatPageTree(PermissionTreeVO.toVOList(list)),rolePermissionIdList,new ArrayList<Long>());


       return key.get();

    }

    /**
     * 遍历角色权限树结构
     * @param list 权限树结构
     * @param rolePermissionIdList 角色当前权限id列表
     * @param idList 用于存放id列表
     */
    public List<PermissionTreeVO> test(List<PermissionTreeVO> list,List<Long> rolePermissionIdList,List<Long> idList){

        List<PermissionTreeVO> collect = list.stream().map(v -> {
            if (v.getChildren().size() > 0) {
                PermissionTreeVO a = PermissionTreeVO.voTovo(v);
                List<PermissionTreeVO> children = a.getChildren();
                a.setChildren(test(children,rolePermissionIdList,idList));
                return a;
            } else {
                List<Long> collect1 = rolePermissionIdList.stream()
                        .filter(v1 -> v1 == v.getId()).collect(Collectors.toList());

                if (collect1.size()!=0) {
                    idList.add(collect1.get(0));
                }
                key.set(idList);
                return v;
            }
        }).collect(Collectors.toList());
        return collect;
    }
}

